package user_fav

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"shop_webs/userop_web/api"
	"shop_webs/userop_web/forms"
	"shop_webs/userop_web/global"
	"shop_webs/userop_web/proto"
	"strconv"
)

func List(ctx *gin.Context) {
	userId := ctx.GetInt("userId")
	goodsId, _ := strconv.Atoi(ctx.Query("goodsId"))
	zap.S().Infoln("当前用户是", userId)
	rsp, err := global.UserFavClient.GetUserFavList(context.Background(), &proto.UserFavRequest{
		UserId:  int32(userId),
		GoodsId: int32(goodsId),
	})
	if err != nil {
		zap.S().Errorw("[List] 查询 【收藏列表】失败", "msg", err.Error())
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	if rsp.Total == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"total": 0,
		})
		return
	}

	var goodIds []int32
	for _, item := range rsp.Data {
		goodIds = append(goodIds, item.GoodsId)
	}

	//请求商品服务获取商品信息
	goodsRsp, err := global.GoodsClient.BatchGetGoods(context.Background(), &proto.BatchGoodsIdInfo{
		Id: goodIds,
	})
	if err != nil {
		zap.S().Errorw("[List] 批量查询 【商品列表】失败", "msg", err.Error())
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	/*		前端格式
			{
				"total":12,
				"data":[
					{
						"id":1,
						"goods_id":421,
						"goods_name":421,
						"goods_price":421,
						"goods_image":421,
						"nums":421,
						"checked":421,
					}
				]
			}
	*/
	var goodsList []map[string]interface{}
	for _, item := range rsp.Data {
		for _, good := range goodsRsp.Data {
			if item.GoodsId == good.Id {
				goodsList = append(goodsList, map[string]interface{}{
					"id":         item.GoodsId,
					"name":       good.Name,
					"shop_price": good.ShopPrice,
				})
			}
		}
	}

	ctx.JSON(http.StatusOK, gin.H{
		"total": goodsRsp.Total,
		"data":  goodsList,
	})
}
func New(ctx *gin.Context) {
	//添加收藏
	userFavForm := forms.UserFavForm{}
	if err := ctx.ShouldBind(&userFavForm); err != nil {
		api.HandleValidatorError(err, ctx)
		return
	}

	//为了严谨性，添加商品到收藏之前，记得检查一下商品是否存在
	_, err := global.GoodsClient.GetGoodsDetail(context.Background(), &proto.GoodInfoRequest{
		Id: userFavForm.GoodsId,
	})
	if err != nil {
		zap.S().Errorw("[List] 查询 【商品信息】失败", "msg", err.Error())
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	userId := ctx.GetInt("userId")
	_, err = global.UserFavClient.CreateUserFav(context.Background(), &proto.UserFavRequest{
		GoodsId: userFavForm.GoodsId,
		UserId:  int32(userId),
	})
	if err != nil {
		zap.S().Errorw("添加收藏失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusBadRequest, nil)
}
func Delete(ctx *gin.Context) {
	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}

	_, err = global.UserFavClient.DeleteUserFav(context.Background(), &proto.UserFavRequest{
		UserId:  int32(ctx.GetInt("userId")), //防止删除别人
		GoodsId: int32(i),
	})
	if err != nil {
		zap.S().Errorw("删除收藏记录失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.Status(http.StatusOK)
}
func Detail(ctx *gin.Context) {
	goodsId := ctx.Param("id")
	goodsIdInt, err := strconv.ParseInt(goodsId, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}
	userId, _ := ctx.Get("userId")
	_, err = global.UserFavClient.GetUserFavDetail(context.Background(), &proto.UserFavRequest{
		UserId:  int32(userId.(uint)),
		GoodsId: int32(goodsIdInt),
	})
	if err != nil {
		zap.S().Errorw("查询收藏状态失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.Status(http.StatusOK)
}
